package com.esoon.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.esoon.chatarea.MainActivity;
import com.esoon.smartsee.R;
import com.esoon.utils.AlertDialogCommon;
import com.mb.voip.api.MBVoipClientApp;
import com.mb.voip.api.VTCallStateListener;
import com.mb.voip.api.VideoPhone;
import com.mb.voip.api.VideoPhoneDataBean;
import com.mb.voip.api.mbVTCallsManager;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AFragment extends Fragment implements VTCallStateListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private SharedPreferences sharedPreferences1;
    private SharedPreferences.Editor editor1;
    private String mParam1;
    private String mParam2;
    private ImageButton hungup;
    private ImageButton backoLogin;
    private Button webchatLogin;
    private static Timer timer;

    public static AlertDialogCommon callingServiceDialog;
    ImageButton robotButton;
    private OnFragmentInteractionListener mListener;
    private View.OnKeyListener backlistener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (i == KeyEvent.KEYCODE_BACK) {  //表示按返回键 时的操作

                    final AlertDialogCommon exitdialog = new AlertDialogCommon(getActivity(), R.layout.dialog_commom);
                    exitdialog.showDialog();
                    Button sure = exitdialog.getView().findViewById(R.id.submit);
                    sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MBVoipClientApp client = MBVoipClientApp.getVoipClientApp();
                            client.unregister();
                            getActivity().moveTaskToBack(true);
                            exitdialog.dismiss();
                        }
                    });
                    Button exit = exitdialog.getView().findViewById(R.id.cancel);
                    exit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            exitdialog.dismiss();
                        }
                    });
                    //后退
                    return false;    //已处理
                }
            }
            return false;
        }
    };

    public AFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AFragment.
     */
    // TODO: Rename and change types and number of parameters

    @BindView(R.id.imageBinner)
    ImageView banner;

    public static AFragment newInstance(String param1, String param2) {
        AFragment fragment = new AFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        if (callingServiceDialog != null) {
            callingServiceDialog.dismiss();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (callingServiceDialog != null) {
            callingServiceDialog.dismiss();
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_a, container, false);


        if (sharedPreferences == null) {
            sharedPreferences = getActivity().getSharedPreferences("smartsee", getActivity().MODE_PRIVATE);
        }

        editor = sharedPreferences.edit();
        if (sharedPreferences1 == null) {
            sharedPreferences1 = getActivity().getSharedPreferences("sign", getActivity().MODE_PRIVATE);
        }
        editor1 = sharedPreferences1.edit();

        view.setFocusable(true);//这个和下面的这个命令必须要设置了，才能监听back事件。
        view.setFocusableInTouchMode(true);
        view.setOnKeyListener(backlistener);

        robotButton = view.findViewById(R.id.robot);
        backoLogin = view.findViewById(R.id.backoLogin);
        webchatLogin = view.findViewById(R.id.webchatLogin);
       /* webchatLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
            }
        });*/
        backoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final AlertDialogCommon exitdialog = new AlertDialogCommon(getActivity(), R.layout.dialog_commom);
                exitdialog.showDialog();
                TextView title = exitdialog.getView().findViewById(R.id.title);
                Button sure = exitdialog.getView().findViewById(R.id.submit);
                title.setText("您确定要注销么？");
                sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MBVoipClientApp client = MBVoipClientApp.getVoipClientApp();
                        client.unregister();
                        client.ReleaseVoipClient();
                       /* editor.clear();
                        editor.commit();*/
                        editor1.clear();
                        editor1.commit();
                        //   getActivity().finish();
             /*           Intent intent=new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);*/
                        android.os.Process.killProcess(android.os.Process.myPid());
                        exitdialog.dismiss();
                    }
                });
                Button exit = exitdialog.getView().findViewById(R.id.cancel);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        exitdialog.dismiss();
                    }
                });
            }
        });
        robotButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCallingDialog("81001");
           /*  TimerTask timerTask=new TimerTask() {
                 @Override
                 public void run() {
                     if (callingServiceDialog!=null){
                         callingServiceDialog.dismiss();


                     }
                 }
             };*/
               /* final AlertDialogCommon calldialog = new AlertDialogCommon(getActivity(), R.layout.dialog_call);
                final EditText callNum = calldialog.getView().findViewById(R.id.callNumber);
                TextView title = calldialog.getView().findViewById(R.id.title);
                Button sure = calldialog.getView().findViewById(R.id.submit);
                Button cancel = calldialog.getView().findViewById(R.id.cancel);

                title.setText("请输入要拨打的号码");
                sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        calldialog.dismiss();

                    }
                });

               cancel.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       calldialog.dismiss();
                   }
               });
                calldialog.showDialog();*/

            }
        });

        return view;


    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    public void showCallingDialog(String number) {

        //Toast.makeText(getActivity(), "正在拨打" + number, Toast.LENGTH_SHORT).show();
        MBVoipClientApp client = MBVoipClientApp.getVoipClientApp();
        client.Dial(number, true, 3, 3);
        callingServiceDialog = new AlertDialogCommon(getActivity(), R.layout.activity_calling_service);
        callingServiceDialog.showDialog();
        WindowManager ctim = getActivity().getWindowManager();
        Display ctid = ctim.getDefaultDisplay(); //为获取屏幕宽、高
        WindowManager.LayoutParams ctip = callingServiceDialog.getWindow().getAttributes();//获取对话框当前的参数值
        ctip.height = ctid.getHeight() * 1; //高度设置为屏幕的0.3
        ctip.width = ctid.getWidth() * 1; //宽度设置为屏幕的0.5
        callingServiceDialog.getWindow().setAttributes(ctip); //设置生效
        Window ctidialogWindow = callingServiceDialog.getWindow();
        WindowManager.LayoutParams ctilp = ctidialogWindow.getAttributes();

        hungup = callingServiceDialog.getView().findViewById(R.id.hungup);
        hungup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MBVoipClientApp client = MBVoipClientApp.getVoipClientApp();
                mbVTCallsManager callsManager = mbVTCallsManager.getManager();
                int callid = callsManager.getActiveCallId();
                client.DropCall(callid);
                callingServiceDialog.dismiss();
            }
        });


        ctidialogWindow.setAttributes(ctilp);


    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onVTCallStateChanged(VideoPhone videoPhone, int i, int state, int i2, int i3, Object o) {


        switch (state) {

            case VideoPhoneDataBean.MBVoipCall_Disonnected:

                callingServiceDialog.dismiss();
                break;


        }


    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


}
